﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace NerdWare.Crm2011VsTools.CrmScriptInjector
{
    using System.IO;

    class FileMonitor
    {
        /// <summary>
        /// This is the current Folder to be watched. Folder can be changed anytime.
        /// </summary>
        private string _parentFolder;

        internal FileMonitor()
        {
            //NTrace.Default.Info("File-Monitor initialized.");
        }

        internal int ContainCounter(string key)
        {
            if (Files.Contains(key))
                return Files[key].Count();

            return 0;
        }

        internal string GetFileContent(string key)
        {
            return File.ReadAllText(Files[key].First());
        }

        /// <summary>
        /// Gets the files.
        /// </summary>
        /// <param name="parentFolder">The parent folder.</param>
        /// <param name="force">if set to <c>true</c> [force].</param>
        /// <remarks>
        /// It verifies, if the folder has changed too. If the folder changed, it will reparse the complete list.
        /// </remarks>
        internal void GetFiles(string parentFolder, bool force = false)
        {
            if (!Path.IsPathRooted(parentFolder))
            {
                //NTrace.Default.Error(() => string.Format("Parentfolder '{0}' is not rooted!", parentFolder));
                return;
            }

            if (_parentFolder == parentFolder && !force)
            {
                //NTrace.Default.Debug(() => string.Format("Parentfolder '{0}' has not changed. No need to reload the list.", parentFolder));
                return;
            }

            if (force){}
                //NTrace.Default.Debug("Forced reload of Parentfolder '{0}'", _parentFolder);
            else
            {
                //NTrace.Default.Debug("Changing Parentfolder to '{0}'. Oldpath was '{1}'", parentFolder, _parentFolder);
                _parentFolder = parentFolder;
            }

            List<string> fileList = new List<string>();
            try
            {
                //NTrace.Default.Debug("Parsing Parentfolder '{0}'", _parentFolder);
                fileList.AddRange(Directory.GetFiles(_parentFolder, "*.js", SearchOption.AllDirectories));
                Files = (Lookup<string, string>)fileList.ToLookup(s =>
                {
                    var fileName = Path.GetFileName(s);
                    return fileName != null ? fileName.ToLower() : null;
                }, s => s);

                //NTrace.Default.Debug("Parentfolder parsed. Identified {0} file(s).", Files.Count);
            }
            catch (Exception ex)
            {
                //NTrace.Default.ErrorException(string.Format("Error in reading directory '{0}'", _parentFolder), ex);
                throw;
            }
        }

        private readonly object _filesLock = new object();
        private Lookup<string, string> _files;
        public Lookup<string, string> Files
        {
            get
            {
                lock (_filesLock)
                {
                    return _files;
                }
            }
            private set
            {
                lock (_filesLock)
                {
                    _files = value;
                }
            }
        }
    }
}
